package wang.xinqiu.mysqlcontrol.data

import android.content.Context
import android.content.SharedPreferences
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.decodeFromString

class PreferencesManager(context: Context) {
    private val masterKey = MasterKey.Builder(context)
        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
        .build()

    private val sharedPreferences: SharedPreferences = EncryptedSharedPreferences.create(
        context,
        "mysql_connection_prefs",
        masterKey,
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
    )

    fun saveConnectionInfo(connectionInfo: ConnectionInfo) {
        val connections = getConnectionHistory().toMutableList()
        connections.removeAll { it.host == connectionInfo.host && it.port == connectionInfo.port }
        connections.add(0, connectionInfo)
        
        if (connections.size > 10) {
            connections.removeAt(connections.size - 1)
        }
        
        val json = Json.encodeToString(connections)
        sharedPreferences.edit().putString("connection_history", json).apply()
    }

    fun getConnectionHistory(): List<ConnectionInfo> {
        val json = sharedPreferences.getString("connection_history", null)
        return if (json != null) {
            try {
                Json.decodeFromString<List<ConnectionInfo>>(json)
            } catch (e: Exception) {
                emptyList()
            }
        } else {
            emptyList()
        }
    }

    fun clearConnectionInfo() {
        sharedPreferences.edit().clear().apply()
    }

    fun saveLastConnection(connectionInfo: ConnectionInfo) {
        val json = Json.encodeToString(connectionInfo)
        sharedPreferences.edit().putString("last_connection", json).apply()
    }

    fun getLastConnection(): ConnectionInfo? {
        val json = sharedPreferences.getString("last_connection", null)
        return if (json != null) {
            try {
                Json.decodeFromString<ConnectionInfo>(json)
            } catch (e: Exception) {
                null
            }
        } else {
            null
        }
    }

    fun clearLastConnection() {
        sharedPreferences.edit().remove("last_connection").apply()
    }

    fun saveConnectionHistory(connections: List<ConnectionInfo>) {
        val json = Json.encodeToString(connections)
        sharedPreferences.edit().putString("connection_history", json).apply()
    }

    // 查询历史管理方法
    fun getQueryHistory(databaseName: String): List<String> {
        val key = "query_history_$databaseName"
        val json = sharedPreferences.getString(key, null)
        return if (json != null) {
            try {
                Json.decodeFromString<List<String>>(json)
            } catch (e: Exception) {
                emptyList()
            }
        } else {
            emptyList()
        }
    }

    fun saveQueryHistory(databaseName: String, history: List<String>) {
        val key = "query_history_$databaseName"
        val json = Json.encodeToString(history)
        sharedPreferences.edit().putString(key, json).apply()
    }

    fun clearQueryHistory(databaseName: String) {
        val key = "query_history_$databaseName"
        sharedPreferences.edit().remove(key).apply()
    }
    
    // 新增：智能查询建议历史
    fun saveQuerySuggestions(databaseName: String, suggestions: List<String>) {
        val key = "query_suggestions_$databaseName"
        val json = Json.encodeToString(suggestions)
        sharedPreferences.edit().putString(key, json).apply()
    }
    
    fun getQuerySuggestions(databaseName: String): List<String> {
        val key = "query_suggestions_$databaseName"
        val json = sharedPreferences.getString(key, null)
        return if (json != null) {
            try {
                Json.decodeFromString<List<String>>(json)
            } catch (e: Exception) {
                emptyList()
            }
        } else {
            emptyList()
        }
    }
    
    // 新增：保存表结构缓存
    fun saveTableStructure(databaseName: String, tableName: String, structure: QueryResult) {
        val key = "table_structure_${databaseName}_$tableName"
        val json = Json.encodeToString(structure)
        sharedPreferences.edit().putString(key, json).apply()
    }
    
    fun getTableStructure(databaseName: String, tableName: String): QueryResult? {
        val key = "table_structure_${databaseName}_$tableName"
        val json = sharedPreferences.getString(key, null)
        return if (json != null) {
            try {
                Json.decodeFromString<QueryResult>(json)
            } catch (e: Exception) {
                null
            }
        } else {
            null
        }
    }
    
    // 新增：保存用户偏好的查询模板
    fun saveQueryTemplates(templates: List<QueryTemplate>) {
        val json = Json.encodeToString(templates)
        sharedPreferences.edit().putString("query_templates", json).apply()
    }
    
    fun getQueryTemplates(): List<QueryTemplate> {
        val json = sharedPreferences.getString("query_templates", null)
        return if (json != null) {
            try {
                Json.decodeFromString<List<QueryTemplate>>(json)
            } catch (e: Exception) {
                getDefaultQueryTemplates()
            }
        } else {
            getDefaultQueryTemplates()
        }
    }
    
    private fun getDefaultQueryTemplates(): List<QueryTemplate> {
        return listOf(
            QueryTemplate("基础查询", "SELECT * FROM table_name WHERE condition;"),
            QueryTemplate("插入数据", "INSERT INTO table_name (column1, column2) VALUES (value1, value2);"),
            QueryTemplate("更新数据", "UPDATE table_name SET column1 = value1 WHERE condition;"),
            QueryTemplate("删除数据", "DELETE FROM table_name WHERE condition;"),
            QueryTemplate("创建表", "CREATE TABLE table_name (\n  id INT PRIMARY KEY AUTO_INCREMENT,\n  name VARCHAR(255) NOT NULL\n);"),
            QueryTemplate("联表查询", "SELECT t1.*, t2.* FROM table1 t1 LEFT JOIN table2 t2 ON t1.id = t2.table1_id;"),
            QueryTemplate("分组统计", "SELECT column, COUNT(*) as count FROM table_name GROUP BY column ORDER BY count DESC;"),
            QueryTemplate("查看表结构", "DESCRIBE table_name;"),
            QueryTemplate("显示所有表", "SHOW TABLES;"),
            QueryTemplate("显示数据库", "SHOW DATABASES;")
        )
    }
}

@kotlinx.serialization.Serializable
data class QueryTemplate(
    val name: String,
    val template: String
)